package com.test.testauth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.test.testauth.Vo.AjaxResult;
import com.test.testauth.Vo.InstructDTO;
import com.test.testauth.Vo.InstructParam;
import com.test.testauth.enums.VisualizationMethod;
import com.test.testauth.service.SpecificService;
import com.test.testauth.service.UavNestCentralService;
import com.test.testauth.utils.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**

 * @author ：wang qiang
 * @date ：Created 2024/8/1 17:07
 * @description：无人机与机巢统一实现
 */
@Service
public class UavNestCentralServiceImpl implements UavNestCentralService {
    private static final Logger log = LoggerFactory.getLogger(UavNestCentralServiceImpl.class);
    @Override
    public AjaxResult<InstructDTO> UavSendInstruct(InstructParam param) {
        return getInstructDTOAjaxResult(param);
    }

    @Override
    public AjaxResult<InstructDTO> NestSendInstruct(InstructParam param) {
        return getInstructDTOAjaxResult(param);
    }


    /**
     * 接口统一方法
     * @param param 接口参数
     */
    private AjaxResult<InstructDTO> getInstructDTOAjaxResult(InstructParam param) {
        AjaxResult<?> returnMessage = syncInstructMethods(param,
                InstructParam.class,
                String.format("%s%s",param.getMethodName(),"Instruct"));
        if(returnMessage.isSuccess()){
            InstructDTO DTO = (InstructDTO)returnMessage.get(AjaxResult.DATA_TAG);
            return new AjaxResult<>(returnMessage.getCode(),returnMessage.getMsg(),DTO);
        }
        return new AjaxResult<>(returnMessage.getCode(), returnMessage.getMsg());
    }

    /**
     * 调用统一方法:通过反射调用具体接口实现类
     * @param paramsClazz 接口参数类型
     * @param params 参数实体对象
     * @param methodName 指定方法名字
     * */
    private AjaxResult<?> syncInstructMethods(Object params,Class<?> paramsClazz,String methodName){
        try{
            String logs = String.format("调用的方法:%s,调用方法参数:%s", methodName, JSONObject.toJSONString(params));
            log.info(logs);
            return (AjaxResult<?>)SpecificService.class
                    .getMethod(methodName,paramsClazz)
                    .invoke(SpringContextUtil.getBean(SpecificService.class),params);
        }catch (Exception e){
            return new AjaxResult<>(VisualizationMethod.returnErrorCode,"调用失败",e.getMessage());
        }
    }
}
